<?php

namespace Sharks\Core\Persistence\QueryBuilder;
use Sharks\Core\Persistence\Db;
use Sharks\Core\Support\Log\Log;

/**
 * SQL Update
 * <pre>
 *      Query::createUpdate()->table('SysUser')->set('loginname', 'root')->get(); // 更新该表的login列
 *      Query::createUpdate()->table('SysUser')->set('loginname', 'root')->eq('id', 1)->get(); //更新id=1的行中loginname列数据
 * </pre>
 */
class UpdateQuery extends AbstractExpressionQuery {

    protected $updateQuery;

    public function __construct($identifier) {
        $this->updateQuery = Db::connector($identifier)->createUpdateQuery();
    }

    public function table($table) {
        $this->updateQuery->update($table);
        return $this;
    }

    public function set($column, $value) {
        $this->updateQuery->set($column, $this->updateQuery->bindValue($value));
        return $this;
    }

    public function sets(array $datas) {
        foreach ($datas as $column => $value) {
            $this->set($column, $value);
        }
        return $this;
    }

    public function get() {
        $stmt = $this->updateQuery->prepare();
        $stmt->execute();
        $this->checkError($stmt);
        $rowCount = $stmt->rowCount();
        if ($rowCount == 0) {
            Log::debug("更新影响行数为0");
        }
        return $rowCount;
    }

    protected function getQuery() {
        return $this->updateQuery;
    }
}